//
// Created by 原帅 on 2022/11/6.
//

#include "RMessageDispatcher.h"
#include "RMessage.pb.h"
#include "RMsgID.pb.h"
#include "RLog.h"

int RMessageDispatcher::dispatch(RMSG::RMessage& msg) {
    if (!msg.has_header())
    {
        RLogErr("RMessage has not header!")
        return -1;
    }
    if (mapDispatcher.count(msg.header().rmsgid()))
    {
        std::vector<RMsgProc*> &msgProccessors = mapDispatcher.at(msg.header().rmsgid());
        for (auto proc : msgProccessors) {
            proc->procDispatchMessage(msg);
            if (msg.heartbeat().rmsgid()== RMSG::RMSG_HEART_BEAT)
            {

            }
        }
    }
    return 0;
}

RMessageDispatcher * RMessageDispatcher::addDispatchProcessor(RMSG::RMessageId msgid, RMsgProc *msgProc) {
    if (mapDispatcher.count(msgid))
    {
        std::vector<RMsgProc*> &vecProc = mapDispatcher.at(msgid);
        if (std::find(vecProc.begin(),vecProc.end(),msgProc)==vecProc.end())
        {
            vecProc.push_back(msgProc);
        } else {
            RLogErr("there is a same one dispatch proc in vector! ingore this one")
        }
    } else {
        std::vector<RMsgProc*> vecProc;
        vecProc.push_back(msgProc);
        mapDispatcher.insert(std::pair<RMSG::RMessageId,std::vector<RMsgProc*>>(msgid,vecProc));
    }
    return this;
}
